package com.github.thinwonton.activemq.showcase.ack.mode.transacted;

import com.github.thinwonton.activemq.showcase.ActiveMQManager;

import javax.jms.*;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Sender {

    private static Connection connection;

    static {
        try {
            connection = ActiveMQManager.createConnection();
        } catch (JMSException e) {
            e.printStackTrace();
        }
    }

    public void sendMessage(String message) throws JMSException {
        Session session = connection.createSession(true, Session.SESSION_TRANSACTED);
        Queue queue = session.createQueue(Utils.QUEUE_NAME);
        MessageProducer producer = session.createProducer(queue);
        TextMessage toMessage = session.createTextMessage(message);
        producer.send(toMessage);
        session.commit(); //如果不提交事务，消息不会进入broker队列
        producer.close();
        session.close();
    }

    public void close() {
        if (connection != null) {
            try {
                connection.close();
            } catch (JMSException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        Sender sender = new Sender();
        SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
        for (int i = 0; i < 5; i++) {
            String date = dateFormat.format(new Date());
            String message = String.format("msg[%s][%s]", i, date);
            try {
                sender.sendMessage(message);
                System.out.println("消息发送成功：" + message);
                Thread.sleep(1000); //1秒发送一条
            } catch (JMSException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }

        sender.close();
    }
}
